import UIKit

// 箱子
class Box: BaseGameObject {
    private var mBack: BaseGameObject!      // 背后对象
    internal var mCurrentImage: UIImage!    // 当前图片
    internal var mImage2: UIImage!          // 图片2

    /**
     * 构造方法。
     * @param back      背后对象
     * @param drawer    绘图者
     * @param type      类型
     * @param x, y      左上角坐标
     */
    public init(_ back: BaseGameObject, drawer: CGContext, type: _Type, x: Int, y: Int) {
        super.init(drawer, type: type, x: x, y: y)

        // 初始化成员
        mBack = back
        mCurrentImage = mImage
        let imageFileName = String(format: Const.IMAGE_FILE_NAME, type.rawValue * 10 + 1)
        mImage2 = super.loadImage(imageFileName)
    }

    /**
     * 移动。
     * @param direction     方向
     * @param moveReuslt    移动结果
     * @return 被推动的箱子
     */
    public override func move(_ direction: Int, moveResult: inout MoveResult) -> BaseGameObject! {
        var leftFromDest = false    // 是否离开目的地
        var destX = mX, destY = mY  // 新位置的坐标

        if direction == Const.TAG_BUTTON_LEFT {
            destX -= 1
        } else if direction == Const.TAG_BUTTON_RIGHT {
            destX += 1
        } else if direction == Const.TAG_BUTTON_UP {
            destY -= 1
        } else if direction == Const.TAG_BUTTON_DOWN {
            destY += 1
        }

        // 如果旁边是墙或箱子，则直接返回
        if Game.sBaseGameObjects[destY][destX].type == _Type.WALL ||
            Game.sBaseGameObjects[destY][destX].type == _Type.BOX {
            moveResult = .NO_MOVE
            return nil
        }

        // 设置移动结果
        if moveResult.rawValue < MoveResult.NORMAL_MOVED.rawValue {
            moveResult = .NORMAL_MOVED
        }

        // 判断是否要离开目的地
        if mType == .BOX && mBack.type == .DESTINATION {
            leftFromDest = true
            moveResult = .LEFT_FROM_DEST
            mCurrentImage = mImage
        }

        // 用背后对象擦除自己
        mBack.draw()
        Game.sBaseGameObjects[mY][mX] = mBack

        // 计算新位置
        mX = destX
        mY = destY

        // 设置新的背后对象
        mBack = Game.sBaseGameObjects[mY][mX]

        // 判断是否到达目的地
        if mType == .BOX && mBack.type == .DESTINATION {
            if leftFromDest {
                moveResult = .NORMAL_MOVED
            } else {
                moveResult = .ARRIVED_ON_DEST
            }
            mCurrentImage = mImage2
        }

        // 重绘自己
        let rect = CGRect(x: mX * BaseGameObject.sSize, y: mY * BaseGameObject.sSize, width: BaseGameObject.sSize, height: BaseGameObject.sSize)
        mDrawer.draw(mCurrentImage.cgImage!, in: rect)

        // 将自己保存到数组中
        Game.sBaseGameObjects[mY][mX] = self

        return self
    }
}
